<template>
  <div class="flex flex-wrap gap-4" >
    <el-breadcrumb style="margin-bottom: 20px;">
    <el-breadcrumb-item><b>数据筛选</b></el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 信息搜索 -->
    <el-card style="width: 1800px" shadow="always">
      <el-button type="success" plain @click="dialogFormVisible = true" style="margin-bottom: 25px;">高级搜索</el-button>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="退货单号">
      <el-input v-model="formInline.user" placeholder="请输入/扫描单号" clearable />
      </el-form-item>

      <el-form-item label="采购单号">
      <el-input v-model="formInline.user" placeholder="请输入/扫描单号" clearable />
      </el-form-item>

      <el-form-item label="产品名称">
      <el-input v-model="formInline.user" placeholder="请输入/扫描单号" clearable />
      </el-form-item>

      <el-form-item label="订单状态">
      <el-select
      v-model="formInline.region"
      placeholder="请选择"
      clearable
      >
      <el-option label="Zone one" value="shanghai" />
      <el-option label="Zone two" value="beijing" />
      </el-select>
      </el-form-item>

      <el-form-item>
      <el-button type="primary" @click="purchaseshow()">搜索</el-button>
      <el-button  @click="onSubmit">重置</el-button>
      </el-form-item>
      </el-form>
    </el-card>
  </div>
  <!-- 数据显示信息 -->
  <div class="flex flex-wrap gap-4" style="margin-top: 20px;">
         <el-button type="success" @click="handleClick">+新增退货</el-button>
     <el-button type="info" @click="purchaseshow()">刷新</el-button>
     <el-button type="warning" @click="clearAllReturnData">清空数据</el-button>
     <el-button type="primary" @click="handleExport">导出</el-button>
     <el-button type="danger" @click="batchDeleteReturns" :disabled="selectedRows.length === 0">批量删除</el-button>
    <el-card style="width: 1800px" shadow="always">
        <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="purchase_Number" label="退货单号" width="100" />
        <el-table-column prop="product_Name" label="产品名称" width="100" />
        <el-table-column prop="Product_Number" label="产品编号" width="100" />
        <el-table-column prop="Specifications" label="产品规格" width="100" />
        <el-table-column prop="Storage_Unit" label="单位" width="100" />
        <el-table-column prop="Price" label="单价" width="100" />
        <el-table-column prop="Product_Num" label="数量" width="100" />
        <!-- <el-table-column prop="date" label="总额" width="100" /> -->
        <el-table-column prop="Carrier_Name" label="供应商名称" width="100" />
        <el-table-column prop="name" label="订单总额" width="100" />
        <el-table-column prop="Purchase_State" label="状态" width="100" />
        <el-table-column prop="CreateTime" label="创建时间" width="100" />
        <el-table-column  label="操作" width="150">
          <template #default="scope">
            <el-button type="info" size="small" @click="viewReturnDetails(scope.row)">查看</el-button>
            <el-button type="danger" size="small" @click="deleteReturn(scope.row)">删除</el-button>
          </template>
        </el-table-column>
        </el-table>
    </el-card>
  </div>

  <!-- 高级搜索弹出框 -->
  <el-dialog v-model="dialogFormVisible" title="高级搜索" width="500">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="退货单号">
    <el-input v-model="formInline.user"  clearable />
    </el-form-item>

    <el-form-item label="采购单号">
    <el-input v-model="formInline.user"  clearable />
    </el-form-item>

    <el-form-item label="产品编号">
    <el-input v-model="formInline.user"  clearable />
    </el-form-item>

    <el-form-item label="产品名称">
    <el-input v-model="formInline.user"  clearable />
    </el-form-item>

    <el-form-item label="供应商编号">
    <el-input v-model="formInline.user"  clearable />
    </el-form-item>

    <el-form-item label="供应商名称">
    <el-input v-model="formInline.user"  clearable />
    </el-form-item>


    <el-form-item label="起始时间">
    <el-date-picker
    v-model="formInline.date"
    type="date"
    placeholder="Pick a date"
    clearable
    />
    </el-form-item>
    <el-form-item>
    <el-button type="primary" @click="onSubmit">查询</el-button>
    </el-form-item>
    </el-form>
    <!-- <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">
          Confirm
        </el-button>
      </div>
    </template> -->
  </el-dialog>

  <!-- 退货详情弹出框 -->
  <el-dialog v-model="detailDialogVisible" title="退货详情" width="800" :before-close="handleCloseDetail">
    <div class="detail-container">
      <!-- 基本信息 -->
      <div class="basic-info">
        <h3>基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>退货单号：</label>
              <span>{{ currentReturnDetail.purchase_Number }}</span>
            </div>
            <div class="info-item">
              <label>采购单号：</label>
              <span>{{ currentReturnDetail.Purchase_Number || 'N/A' }}</span>
            </div>
            <div class="info-item">
              <label>联系人：</label>
              <span>{{ currentReturnDetail.Contact_Person || 'N/A' }}</span>
            </div>
            <div class="info-item">
              <label>电话：</label>
              <span>{{ currentReturnDetail.Phone || 'N/A' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>单据类型：</label>
              <span>{{ currentReturnDetail.Document_Type || '实际订单' }}</span>
            </div>
            <div class="info-item">
              <label>制单人：</label>
              <span>{{ currentReturnDetail.Preparer || 'N/A' }}</span>
            </div>
            <div class="info-item">
              <label>供应商编号：</label>
              <span>{{ currentReturnDetail.Supplier_ID || 'N/A' }}</span>
            </div>
            <div class="info-item">
              <label>备注：</label>
              <span>{{ currentReturnDetail.Remarks || 'N/A' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>单据状态：</label>
              <span>{{ currentReturnDetail.Purchase_State || '创建订单' }}</span>
            </div>
            <div class="info-item">
              <label>制单日期：</label>
              <span>{{ formatDate(currentReturnDetail.CreateTime) }}</span>
            </div>
            <div class="info-item">
              <label>供应商名称：</label>
              <span>{{ currentReturnDetail.Carrier_Name || 'N/A' }}</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 产品详情表格 -->
      <div class="product-details">
        <h3>产品详情</h3>
        <el-table :data="[currentReturnDetail]" border style="width: 100%">
          <el-table-column prop="Product_Number" label="产品编码" width="120" />
          <el-table-column prop="product_Name" label="产品名称" width="150" />
          <el-table-column prop="Specifications" label="规格" width="100" />
          <el-table-column prop="Storage_Unit" label="单位" width="80" />
          <el-table-column prop="Product_Num" label="数量" width="100" />
          <el-table-column prop="Batch_Number" label="批次" width="100" />
          <el-table-column prop="Return_Quantity" label="退货数" width="100" />
          <el-table-column prop="Price" label="单价" width="100" />
          <el-table-column prop="name" label="总额" width="100" />
        </el-table>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirmReturn">确认</el-button>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { BusinessRed } from '@/http/axiosHelper'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { statementRed } from '@/http/axiosHelper'
import moment from 'moment';

const router = useRouter();

//生命周期钩子函数
onMounted((): void => {
  // 检查是否有新的退货数据
  checkReturnData();
  // 加载持久化的退货数据
  loadPersistentReturnData();
  purchaseshow();
})

// 检查退货数据
const checkReturnData = (): void => {
  try {
    const returnData = localStorage.getItem('returnData');
    if (returnData) {
      const parsedData = JSON.parse(returnData);
      // 将退货数据添加到表格中
      addReturnDataToTable(parsedData);
      // 清空localStorage中的数据
      localStorage.removeItem('returnData');
      ElMessage.success('已接收退货信息');
    }
  } catch (error) {
    console.error('处理退货数据失败:', error);
  }
}

// 添加退货数据到表格
const addReturnDataToTable = (returnData: any): void => {
  const { returnOrder, returnProducts } = returnData;
  
  returnProducts.forEach((product: any) => {
    const newReturnRecord = {
      purchase_Number: `RT${Date.now()}`, // 生成退货单号
      product_Name: product.product_Name,
      Product_Number: product.product_Number,
      Specifications: product.specifications,
      Storage_Unit: product.storage_Unit,
      Price: product.price,
      Product_Num: product.return_Num, // 退货数量
      Carrier_Name: returnOrder.carrier_Name,
      name: product.total_Amount, // 退货总额
      Purchase_State: '已提交',
      CreateTime: new Date().toISOString()
    };
    
    // 添加到表格数据开头
    tableData.value.unshift(newReturnRecord);
    
    // 保存到localStorage进行持久化存储
    saveReturnDataToStorage(newReturnRecord);
  });
}

// 保存退货数据到localStorage
const saveReturnDataToStorage = (returnRecord: any): void => {
  try {
    // 获取现有的退货数据
    const existingData = localStorage.getItem('persistentReturnData') || '[]';
    const returnDataList = JSON.parse(existingData);
    
    // 添加新的退货记录
    returnDataList.push(returnRecord);
    
    // 保存回localStorage
    localStorage.setItem('persistentReturnData', JSON.stringify(returnDataList));
  } catch (error) {
    console.error('保存退货数据失败:', error);
  }
}

// 从localStorage加载持久化的退货数据
const loadPersistentReturnData = (): void => {
  try {
    const persistentData = localStorage.getItem('persistentReturnData');
    if (persistentData) {
      const returnDataList = JSON.parse(persistentData);
      
      // 将持久化的数据添加到表格中（避免重复添加）
      returnDataList.forEach((record: any) => {
        // 检查是否已经存在于表格中
        const exists = tableData.value.some((item: any) => 
          item.purchase_Number === record.purchase_Number
        );
        
        if (!exists) {
          tableData.value.unshift(record);
        }
      });
      
      console.log(`已加载 ${returnDataList.length} 条持久化退货数据`);
    }
  } catch (error) {
    console.error('加载持久化退货数据失败:', error);
  }
}

//新增退货页面
const handleClick = (): void => {
  // 跳转到采购列表页面，用户可以选择要退货的订单
  router.push({name:'PurchShow'})
}

//数据信息的显示
const data = ref({
    PageIndex: 1,
    PageSize: 15,
    totaCount:0,
    Purchase_Number:'',
    Product_Number:'',
    Product_Name:'',
    Purchase__Supplier:''
})
const tableData = ref<any[]>([])
const purchaseshow = (): void => {
   statementRed.get("api/api/Purchase/PurchaseShow", {
        params: {
            PageIndex: data.value.PageIndex,
            PageSize: data.value.PageSize,
        }
    })
        .then((res: any) => {
            // 获取API数据
            const apiData = res.data.data;
            data.value.totaCount = res.data.totalCount;
            
            // 获取localStorage中已删除的记录ID列表
            const deletedRecords = getDeletedRecordIds();
            
            // 过滤掉已删除的记录
            const filteredData = apiData.filter((item: any) => 
                !deletedRecords.includes(item.purchase_Number)
            );
            
            // 合并API数据和localStorage中的新增数据
            const persistentData = getPersistentReturnData();
            tableData.value = [...persistentData, ...filteredData];
        })
        .catch((err: any) => {
            ElMessage.error("查询失败", err)
        })
}

// 获取已删除记录的ID列表
const getDeletedRecordIds = (): string[] => {
    try {
        const deletedIds = localStorage.getItem('deletedReturnIds');
        return deletedIds ? JSON.parse(deletedIds) : [];
    } catch (error) {
        console.error('获取已删除记录ID失败:', error);
        return [];
    }
}

// 获取持久化的退货数据
const getPersistentReturnData = (): any[] => {
    try {
        const persistentData = localStorage.getItem('persistentReturnData');
        return persistentData ? JSON.parse(persistentData) : [];
    } catch (error) {
        console.error('获取持久化退货数据失败:', error);
        return [];
    }
}


// 导出函数（假设已配置 Axios 拦截器自动添加 Token）
async function handleExport(): Promise<void> {
    try {
        // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
        const response = await BusinessRed({
            url: 'api/api/Purchase/GetSellExport', // 后端接口地址
            method: 'GET',
            params: {
                PageIndex: data.value.PageIndex,
                PageSize: data.value.PageSize,
                Product_Number: data.value.Product_Number,
                Product_Name: data.value.Product_Name,
                Purchase_Number: data.value.Purchase_Number,
                Purchase__Supplier: data.value.Purchase__Supplier,
            }, // 对应后端 [FromQuery] 的 command 参数
            responseType: 'blob', // 关键：指定响应类型为二进制流（Excel 文件）
        });

        // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
        const fileName = getFileNameFromHeaders(response.headers);

        // 3. 生成下载链接并触发下载
        const blob = new Blob([response.data], {
            type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName; // 文件名从响应头获取或自定义
        document.body.appendChild(a);
        a.click();

        // 4. 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

    } catch (error: any) {
        // 处理错误（如后端返回 401/400 等）
        console.error('导出失败：', error.response?.data || error.message);
        alert('导出失败，请检查参数或重新登录');
    }
}

// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers: any): string {
    const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
    if (!contentDisposition) return '可出库存.xlsx'; // 默认文件名

    // 解码文件名（处理中文编码问题）
    const match = contentDisposition.match(/filename\*?=([^;]+)/);
    if (match) {
        return decodeURIComponent(match[1].replace(/["']/g, ''));
    }
    return '可出库存.xlsx';
}



//高级搜索弹出框
const dialogFormVisible = ref(false)

// 退货详情弹出框相关
const detailDialogVisible = ref(false)
const currentReturnDetail = ref<any>({})

//条件查询
const formInline = reactive({
  user: '',
  region: '',
  date: '',
})

const onSubmit = (): void => {
  console.log('submit!')
}

// 查看退货详情
const viewReturnDetails = (row: any): void => {
  currentReturnDetail.value = { ...row };
  detailDialogVisible.value = true;
}

// 关闭详情弹出框
const handleCloseDetail = (): void => {
  detailDialogVisible.value = false;
  currentReturnDetail.value = {};
}

// 确认退货
const confirmReturn = (): void => {
  ElMessage.success('退货已确认');
  detailDialogVisible.value = false;
}

// 格式化日期
const formatDate = (dateString: string): string => {
  if (!dateString) return 'N/A';
  try {
    return moment(dateString).format('YYYY-MM-DD HH:mm:ss');
  } catch (error) {
    return dateString;
  }
}

// 删除退货记录
const deleteReturn = (row: any): void => {
  ElMessageBox.confirm(`确定要删除退货单号：${row.purchase_Number} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const index = tableData.value.findIndex((item: any) => item.purchase_Number === row.purchase_Number);
    if (index !== -1) {
      tableData.value.splice(index, 1);
      // 同时从localStorage中删除
      removeReturnDataFromStorage(row.purchase_Number);
      ElMessage.success('删除成功');
    }
  }).catch(() => {
    // 用户取消删除
  });
}

// 批量删除退货记录
const batchDeleteReturns = (): void => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的退货记录');
    return;
  }
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条退货记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const deletedIds = getDeletedRecordIds();
    
    selectedRows.value.forEach((row: any) => {
      const index = tableData.value.findIndex((item: any) => item.purchase_Number === row.purchase_Number);
      if (index !== -1) {
        tableData.value.splice(index, 1);
        removeReturnDataFromStorage(row.purchase_Number);
        
        // 将删除的记录ID添加到已删除列表中
        if (!deletedIds.includes(row.purchase_Number)) {
          deletedIds.push(row.purchase_Number);
        }
      }
    });
    
    // 更新已删除记录列表
    localStorage.setItem('deletedReturnIds', JSON.stringify(deletedIds));
    
    ElMessage.success(`已删除 ${selectedRows.value.length} 条退货记录`);
    selectedRows.value = []; // 清空选中行
  }).catch(() => {
    // 用户取消删除
  });
}

// 从localStorage中删除退货数据
const removeReturnDataFromStorage = (purchaseNumber: string): void => {
  try {
    // 从持久化数据中删除
    const persistentData = localStorage.getItem('persistentReturnData');
    if (persistentData) {
      const returnDataList = JSON.parse(persistentData);
      const filteredList = returnDataList.filter((item: any) => 
        item.purchase_Number !== purchaseNumber
      );
      
      // 更新localStorage
      localStorage.setItem('persistentReturnData', JSON.stringify(filteredList));
    }
    
    // 将删除的记录ID添加到已删除列表中
    const deletedIds = getDeletedRecordIds();
    if (!deletedIds.includes(purchaseNumber)) {
      deletedIds.push(purchaseNumber);
      localStorage.setItem('deletedReturnIds', JSON.stringify(deletedIds));
    }
  } catch (error) {
    console.error('从localStorage删除退货数据失败:', error);
  }
}

// 清空所有退货数据
const clearAllReturnData = (): void => {
  ElMessageBox.confirm('确定要清空所有退货数据吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    try {
      // 清空表格数据
      tableData.value = [];
      // 清空localStorage中的数据
      localStorage.removeItem('persistentReturnData');
      // 清空已删除记录列表
      localStorage.removeItem('deletedReturnIds');
      // 清空选中的行
      selectedRows.value = [];
      ElMessage.success('已清空所有退货数据');
    } catch (error) {
      console.error('清空退货数据失败:', error);
      ElMessage.error('清空数据失败');
    }
  }).catch(() => {
    // 用户取消清空
  });
}

// 选中行变化
const selectedRows = ref<any[]>([]);
const handleSelectionChange = (val: any[]): void => {
  selectedRows.value = val;
}
</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
b{
  color: black;
}

/* 详情弹出框样式 */
.detail-container {
  padding: 20px 0;
}

.basic-info, .product-details {
  margin-bottom: 30px;
}

.basic-info h3, .product-details h3 {
  margin-bottom: 20px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.info-item label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
  margin-right: 10px;
}

.info-item span {
  color: #303133;
  flex: 1;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}

.dialog-footer .el-button {
  margin-left: 10px;
}
</style>